# -*- coding:utf-8 -*-
from openpyxl import load_workbook
from func import *
import os, sys
import datetime

curpath = os.path.normpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
if sys.platform == 'win32':
    enc = 'GBK'
else:
    enc = 'utf-8'

if __name__ == '__main__':
    # 选择文件
    xlsx_list = []
    for fn in os.listdir(curpath):
        if fn.endswith('.xlsx'):
            xlsx_list.append(fn)
    x_index = int(raw_input(prompt_str('choose_file', enc, file_list = xlsx_list).encode(enc)))
    # 读取 excel 文件
    filename = os.path.join(curpath, xlsx_list[x_index - 1])
    wb = load_workbook(filename = filename)
    worksheets = wb.worksheets
    # 选择操作表
    s_index = int(raw_input(prompt_str('choose_sheet', enc, sheets = worksheets).encode(enc)))
    sheet = worksheets[s_index - 1]
    # 获取字段名
    rows = sheet.rows
    fields = []
    parent_field_str = ''
    for i in range(len(rows[1])):
        cell_value = rows[1][i].value
        if cell_value is None:
            cell_value = parent_field_str
        parent_field_str = cell_value
        sub_cell_value = rows[2][i].value
        if sub_cell_value:
            cell_value = "%s - %s" % (cell_value, sub_cell_value)
        cell_value = cell_value.replace(u'\n', '')
        fields.append(cell_value.encode('utf-8'))
    # 读取所有日期
    date_rows = {}
    date_list = []
    date = None
    for i in range(len(rows)):
        if row_is_empty(rows[i]):
            continue
        _date = rows[i][1].value
        date = _date if _date else date
        if not isinstance(date, datetime.datetime):
            continue
        date_rows[date] = date_rows.get(date, [])
        date_rows[date].append(i)
        if not date in date_list:
            date_list.append(date)
    # 选择日期
    d_index = int(raw_input(prompt_str('choose_date', enc, dates = date_list).encode(enc)))
    current_rows = date_rows[date_list[d_index - 1]]
    stat_fields = [5, 6, 7, 8]       # 电转咨询师
    stat_res = dict([(fields[i], {}) for i in stat_fields])
    for i in current_rows:
        for f_index in stat_fields:
            f_name = fields[f_index]
            f_value = rows[i][f_index].value
            if not f_value:
                continue
            f_value = f_value.encode('utf-8')
            stat_res[f_name][f_value] = stat_res[f_name].get(f_value, 0) + 1
    print u'\n======= 统计结果 ========'
    print u'总数：', len(current_rows)
    for k, v in stat_res.items():
        print u"%s：" % unicode(k, 'utf-8')
        v_items = v.items()
        v_items.sort(key = lambda x: x[1], reverse=True)
        for name, num in v_items:
            print u'\t%s： %d' % (unicode(name, 'utf-8'), num)

    # 按任意键退出
    raw_input(u'\n按任意键退出...'.encode(enc))






#sheet = wb.get_sheet_by_name(name = u'3月')
#print sheet.cell('B54').value
